package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Menu;
import cn.wolfcode.crm.service.IMenuService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.MenuUtil;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Component("myFormFilter")
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private IMenuService service;

    protected boolean onLoginSuccess(AuthenticationToken token,
                                     Subject subject, ServletRequest request, ServletResponse response)
            throws Exception {
        //直接响应登录成功的JSON
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //___________________________________
        //如果登录成功,则进行获取菜单操作,减少查询和判断次数,增加效率
        //获取全部节点
        List<Menu> nodes = service.getNodes();
        //判断当前用户是否为超级管理员,如果是,则不进行权限校准
        Employee emp = (Employee) subject.getPrincipal();
        if(!emp.isAdmin()){
            MenuUtil.filtermenu(nodes);
        }
        //将菜单转换为json格式并存储在session中
        req.getSession().setAttribute(MenuUtil.JSON_MENUS_ON_SESSION, nodes);

        try {
            response.setContentType("text/json; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            JsonResult jr = new JsonResult();
            PrintWriter out = response.getWriter();
            out.println(JSON.toJSONString(jr));
            out.flush();
            out.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //如果登录成功,判断其登录用户,然后进入其对应页面
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token,
                                     AuthenticationException e, ServletRequest request,
                                     ServletResponse response) {
        //如果登录失败,抛出异常,进行回调
        try {
            response.setContentType("text/json; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            JsonResult jr = new JsonResult();
            PrintWriter out = response.getWriter();
            String message = e.getClass().getSimpleName();
            if ("IncorrectCredentialsException".equals(message)) {
                jr.setMsg("密码错误");
            } else if ("UnknownAccountException".equals(message)) {
                jr.setMsg("账号不存在");
            } else if ("LockedAccountException".equals(message)) {
                jr.setMsg("账号被锁定");
            } else if ("AuthenticationException".equals(message)) {
                jr.setMsg("账号被锁定");
            } else {
                jr.setMsg("未知错误");
            }
            out.println(JSON.toJSONString(jr));
            out.flush();
            out.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
